#!/usr/bin/env node
//引入websocket模块，http模块，因为前期握手连接还是通过http协议所以这里还要引入
var WebSocketServer = require('websocket').server;
var http = require('http');
var index=0;
var index1=0;
var index2=0;
//创建服务器
var server = http.createServer(function(request, response) {
    console.log((new Date()) + ' Received request for ' + request.url);
    response.writeHead(404);
    response.end();
});
server.listen(3000, function() {
    console.log((new Date()) + '大屏系统服务器启动了......');
});

//新建websocket对象
wsServer = new WebSocketServer({
    httpServer: server,
    // You should not use autoAcceptConnections for production 
    // applications, as it defeats all standard cross-origin protection 
    // facilities built into the protocol and the browser.  You should 
    // *always* verify the connection's origin and decide whether or not 
    // to accept it. 
    autoAcceptConnections: false
});

function originIsAllowed(origin) {//这个是认证，没啥用
    // put logic here to detect whether the specified origin is allowed.
    return true;
}

//这个是websocket建立连接
wsServer.on('request', function(request) {
    if (!originIsAllowed(request.origin)) {
        // Make sure we only accept requests from an allowed origin
        request.reject();
        console.log((new Date()) + ' Connection from origin ' + request.origin + ' rejected.');
        return;
    }
    //当前的连接，因为前端实例化连接对象时候没有写子协议，所以这里第一个参数协议echo-protocol可以不写，直接为空
    var connection = request.accept(null, request.origin);

    setInterval(function(){
        var arr=[];
        index = Math.floor(Math.random() * 50 + 30);
        index1 = Math.floor(Math.random() * 50 + 20);
        index2 = Math.floor(Math.random() * 50 + 200);
        arr.push(index,index1,index2);
        connection.sendUTF(arr);

    },5000)

    console.log((new Date()) + '已经建立连接');
    //监听当前连接，发送message时候，判断前端发来的数据类型是utf8还是二进制
    connection.on('message', function(message) {
        if (message.type === 'utf8') {
            console.log('Received Message: ' + message.utf8Data);
            connection.sendUTF(message.utf8Data);
        }
        else if (message.type === 'binary') {
            console.log('Received Binary Message of ' + message.binaryData.length + ' bytes');
            connection.sendBytes(message.binaryData);
        }
    });

    //监听当前连接关闭时候，触发
    connection.on('close', function(reasonCode, description) {
        console.log((new Date()) + ' Peer ' + connection.remoteAddress + '断开连接');
    });
});